package ru.athena.runTool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

import org.antlr.runtime.CommonTokenStream;

import ru.athena.runTool.Parser.CaseInsensitiveInputStream;
import ru.athena.runTool.Parser.PLSQLLexer;
import ru.athena.runTool.Parser.PLSQLParser;
import ru.athena.runTool.blockTypes.CodeBlock;

public class ScriptParser extends Object{

	private Stack<String> files_ = new Stack<String>();

	/**
	 * Build tree of code blocks started at given root
	 */
	public String getCurrFileName() {
		return (String)files_.peek();
	}

	public List<CodeBlock> parseFile(File	file ) {
		try {
			// begin parsing
			return createParser(file.getCanonicalPath()).compilationUnits();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ArrayList<CodeBlock>();
				
	}

	/**
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private PLSQLParser createParser(String fileName)
			throws FileNotFoundException, IOException {
		PLSQLLexer lexer = createLexer(fileName);
		CommonTokenStream tokens = new CommonTokenStream(lexer);
		PLSQLParser parser = new PLSQLParser(tokens);
		return parser;
	}

	/**
	 * @param fileName
	 * @return
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
	private PLSQLLexer createLexer(String fileName)
			throws FileNotFoundException, IOException {
		FileInputStream fis = new FileInputStream(fileName );
		CaseInsensitiveInputStream	input = 
				new CaseInsensitiveInputStream( fis, "windows-1251");
		PLSQLLexer lexer = new PLSQLLexer( input);
		return lexer;
	}

}